import unittest
from common.logOutput import error

class AssertCommon(unittest.TestCase):
    """"通用断言类：对于返回体内容的断言做了封装。"""
    def __assertIn(self, expect, actual):
        if expect not in actual:
            error_msg = f'The expected field does not exist. expect result:{expect}, actual result:{actual}'
            error('Assert failed!' + error_msg)
            self.fail(error_msg)
    def __assertEqual(self,expect, actual):
        if expect != actual:
            error_msg = f'Does not match the expected result，expect result:{expect}, actual result:{actual}'
            error('Assert failed!' + error_msg)
            self.fail(error_msg)

    def code_assert(self, expect, actual):
        # 对于返回状态码的校验
        if expect != actual:
            error_msg = f'res code different, expect code:{expect}, actual code:{actual}'
            error('Assert failed!' + error_msg)
            self.fail(error_msg)

    def json_assert(self, expect, actual):
        """
        json通用断言方法
        :param expect: 定义预期返回体
        :param actual: 实际返回的json
        :return: 断言成功返回None，断言失败触发fail
        """
        for key, value in expect.items():
            # 校验字段是否存在
            self.__assertIn(key,actual.keys())
        # 校验返回体中是否存在多余字段
        self.__assertEqual(len(expect.keys()), len(actual.keys()))

        for key, value in expect.items():
            # 进行数据类型的校验
            if isinstance(value, type):
                self.__assertEqual(value, type(actual[key]))
            # 对嵌套列表的类型和精准值进行校验
            elif isinstance(value, list):

                for i in range(len(value)):
                    if isinstance(value[i], type):
                        self.__assertEqual(value[i], type(actual[key][i]))
                        # 对于列表字典的嵌套结构，递归判断
                    elif isinstance(value[i], dict):
                        self.json_assert(value[i], actual[key][i])
                    else:
                        self.__assertEqual(value[i], actual[key][i])
            else:
                # 普通字段精准值校验
                self.__assertEqual(value, actual[key])



